<template>
  <PageDialog
    :title="title"
    v-model:visible="showDialog"
    :width="dialogInfo.width"
    :bt-loading="dialogInfo.btLoading"
    :bt-list="dialogInfo.btList"
  >
    <el-row :gutter="20">
      <el-col :span="12">
        <div class="table-top-msg">
          <div class="table-top-msg-left">可选择</div>
          <div class="table-top-msg-left">
            <el-button @click="removeRight">右移</el-button>
          </div>
        </div>
        <DialogTable
          ref="leftTableInfoRef"
          :refresh="leftTableInfo.refresh"
          :init-curpage="leftTableInfo.initCurpage"
          v-model:data="leftTableInfo.data"
          :api="leftTableInfo.api"
          :reserve-selection="true"
          :listen-height="false"
          :check-box="true"
          check-box-fixed="right"
          v-model:query="leftFilterInfo.query"
          :field-list="leftTableInfo.fieldList"
          :handle="leftTableInfo.handle"
          @handleEvent="leftHandleEvent"
        >
        </DialogTable>
      </el-col>
      <el-col :span="12">
        <div class="table-top-msg">
          <div class="table-top-msg-right">
            <el-button @click="removeLeft">左移</el-button>
          </div>
          <div class="table-top-msg-right">已选择</div>
        </div>
        <DialogTable
          ref="rightTableInfoRef"
          v-model:data="rightTableInfo.data"
          :reserve-selection="true"
          :listen-height="false"
          :pager="false"
          :check-box="true"
          checkBoxFixed="left"
          :field-list="rightTableInfo.fieldList"
          :handle="rightTableInfo.handle"
          @handleEvent="rightHandleEvent"
        >
          <template v-slot:col-reason="scope">
            <el-input
              v-if="businessType === '10'"
              v-model="scope.row.reason"
              :maxlength="25"
              @input="(e) => (scope.row.reason = validSe(e))"
            />
            <SelectModel
              v-if="businessType === '1'"
              v-model.lazy="scope.row.reason"
              style="margintop: 18px"
              type-code="purch_return_reason"
            />
          </template>
        </DialogTable>
      </el-col>
    </el-row>
  </PageDialog>
</template>
<script setup name="batchIndividual">
import { getCustomizeSetting } from '@/api/customize'
import _ from 'lodash'
import { computed } from 'vue'
const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps({
  title: {
    type: String,
    default: '个体操作',
  },
  leftApi: {
    type: Function,
  },
  rightApi: {
    type: Function,
  },
  visible: {
    type: Boolean,
  },
  showPrice: {
    type: Boolean,
  },
  leftQuery: {
    type: Object,
    default: function () {
      return {}
    },
  },
  rightQuery: {
    type: Object,
    default: function () {
      return {}
    },
  },
  leftTableKey: {
    type: String,
    default: '',
  },
  rightTableKey: {
    type: String,
    default: '',
  },
  tableRow: {
    type: Object,
    default: function () {
      return {}
    },
  },
  details: {
    type: Array,
    default: function () {
      return []
    },
  },
  isGetRight: {
    type: Boolean,
    default: false,
  },
  businessType: {
    type: String,
    default: '',
  },
})
// 过滤相关配置
const leftFilterInfo = ref({
  query: {
    queryMap: {
      ...props.leftQuery.queryMap,
    },
    queryParams: {
      stockAvailableCalcQtyGt: 0,
      ...props.leftQuery.queryParams,
    },
    customizeUserVO: {},
  },
})
const copyGroupConcatIds = ref(props.tableRow.copyGroupConcatIds)
// 表格相关
const leftTableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  data: [],
  selections: [],
  fieldList: [],
})
const rightTableInfo = ref({
  data: [],
  fieldList: [],
  selections: [],
})
const rightFilterInfo = ref({
  query: {
    queryMap: {
      ...props.rightQuery.queryMap,
    },
    queryParams: {
      stockAvailableCalcQtyGt: 0,
      ...props.rightQuery.queryParams,
    },
    customizeUserVO: {},
  },
})
// 弹窗相关
const dialogInfo = ref({
  btLoading: false,
  width: '90%',
  btList: [
    { label: '关闭', event: handleClose, show: true },
    { label: '保存', event: handleSave, show: true },
  ],
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    emits('update:visible', val) // 更新父组件visible
  },
})
function leftHandleEvent(event, data) {
  if (event === 'list') {
    data.forEach((item) => {
      let unitConvertCoefficient = item.unitConvertCoefficient || 1
      item.diffQty = Math.abs(item.diffQty || 0)
      item.diffCalcQty = Math.abs(item.diffCalcQty || 0)
      item.qty = proxy.$fn.deepClone(item.diffQty)
      item.calcQty = proxy.$fn.deepClone(item.diffCalcQty)
      item.largeUnitQty = parseInt(item.calcQty / unitConvertCoefficient)
      item.smallUnitQty = parseInt(item.calcQty % unitConvertCoefficient)
      item.sumAmount = Math.abs(proxy.$fn.deepClone(item.diffSumAmount || 0))
    })
    leftTableInfo.value.data = data
  }
  if (event === 'tableCheck') {
    leftTableInfo.value.selections = data
  }
}
function rightHandleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      rightTableInfo.value.selections = data
      break
  }
}
function getleftList() {
  leftTableInfo.value.api = props.leftApi
  leftTableInfo.value.refresh = Math.random()
}
// 关闭弹窗前的回调
function handleClose() {
  showDialog.value = false
}
async function removeRight() {
  //左边往右移
  let selections = leftTableInfo.value.selections
  if (selections.length) {
    selections.forEach((item) => {
      item.reason = props.tableRow.reason
    })
    rightTableInfo.value.data = selections.concat(rightTableInfo.value.data)
    let tableIds = rightTableInfo.value.data.map((item) => item.id.toString())
    leftFilterInfo.value.query.queryMap.id.value = tableIds.length
      ? tableIds.toString()
      : ''
    copyGroupConcatIds.value = tableIds.toString()
    getleftList()
  }
  proxy.$refs['leftTableInfoRef'].clearSelection()
}
async function removeLeft() {
  //右边往左移
  let selections = rightTableInfo.value.selections
  if (selections.length) {
    rightTableInfo.value.data = rightTableInfo.value.data.filter(
      (item) => !selections.includes(item)
    )
    let tableIds = rightTableInfo.value.data.map((item) => item.id.toString())
    leftFilterInfo.value.query.queryMap.id.value = tableIds.length
      ? tableIds.toString()
      : ''
    copyGroupConcatIds.value = tableIds.toString()
    getleftList()
  }
  proxy.$refs['rightTableInfoRef'].clearSelection()
}
function handleSave() {
  let calcQty = 0
  if (rightTableInfo.value.data.length) {
    rightTableInfo.value.data.forEach((item) => {
      calcQty = proxy.$fn.accAdd(item.calcQty || 0, calcQty)
    })
  }
  if (calcQty > props.tableRow.diffCalcQty) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '已选个体数量不能大于可用数，请修改',
    })
    return
  }
  emits('callback', rightTableInfo.value.data, copyGroupConcatIds.value)
  handleClose()
}
function getLeftCustomize() {
  let param = { tableKey: props.leftTableKey }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      leftFilterInfo.value.query.customizeUserVO = data
      leftTableInfo.value.fieldList = proxy.$fn.setFieldList(
        leftTableInfo.value.fieldList,
        data.detail
      )
      leftTableInfo.value.fieldList.forEach((item) => {
        if (props.tableRow.codeType === 2) {
          if (
            item.value === 'factoryMainCode' ||
            item.value === 'factorySubCode' ||
            item.value === 'qrCode'
          ) {
            item.hidden = true
          }
        } else if (props.tableRow.codeType === 3) {
          if (item.value === 'uniqueCode' || item.value === 'qrCode') {
            item.hidden = true
          }
        }
      })
      getleftList()
    }
  })
}
function getRightCustomize() {
  let param = { tableKey: props.rightTableKey }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      let num = props.businessType
      rightFilterInfo.value.query.customizeUserVO = data
      rightTableInfo.value.fieldList = proxy.$fn.setFieldList(
        rightTableInfo.value.fieldList,
        data.detail
      )
      rightTableInfo.value.fieldList.forEach((item) => {
        if (num === '2' || num === '20' || num === '34' || num === '25') {
          if (item.value === 'reason') {
            item.hidden = true
          }
        } else if (num === '1') {
          if (item.value === 'reason') {
            item.hidden = false
            item.label = '退货原因'
            item.type = 'slot'
          }
        } else if (num === '10') {
          if (item.value === 'reason') {
            item.hidden = false
            item.label = '报废原因'
            item.type = 'slot'
          }
        }
        if (props.tableRow.codeType === 2) {
          if (
            item.value === 'factoryMainCode' ||
            item.value === 'factorySubCode' ||
            item.value === 'qrCode'
          ) {
            item.hidden = true
          }
        } else if (props.tableRow.codeType === 3) {
          if (item.value === 'uniqueCode' || item.value === 'qrCode') {
            item.hidden = true
          }
        }
      })
      if (props.details && props.details.length) {
        rightTableInfo.value.data = props.details
      } else {
        if (props.isGetRight && props.tableRow.groupConcatIds) {
          getRightList()
        }
      }
    }
  })
}
function getRightList() {
  rightFilterInfo.value.query.queryMap.id.value = props.tableRow.groupConcatIds
  props.rightApi(rightFilterInfo.value.query).then((resp) => {
    if (resp && resp.success && resp.data.length) {
      resp.data.forEach((item) => {
        let unitConvertCoefficient = item.unitConvertCoefficient || 1
        item.diffQty = Math.abs(item.diffQty || 0)
        item.diffCalcQty = Math.abs(item.diffCalcQty || 0)
        item.qty = proxy.$fn.deepClone(item.diffQty)
        item.calcQty = proxy.$fn.deepClone(item.diffCalcQty)
        item.largeUnitQty = parseInt(item.calcQty / unitConvertCoefficient)
        item.smallUnitQty = parseInt(item.calcQty % unitConvertCoefficient)
        item.sumAmount = Math.abs(proxy.$fn.deepClone(item.diffSumAmount || 0))
        item.reason = props.tableRow.reason
      })
      let data = resp.data
      rightTableInfo.value.data = data
    }
  })
}

let obj = {
  commonName: {
    label: '通用名称',
    value: 'commonName',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  price: {
    label: '单价',
    value: 'price',
    minWidth: '150px',
    type: 'slot',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('inventories:price'),
    hidden: true,
  },
  sumAmount: {
    label: '盘点金额',
    value: 'sumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('inventories:price'),
    hidden: true,
    show: false,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('inventories:price'),
    hidden: true,
    show: false,
  },
  diffSumAmount: {
    label: '盘点差异金额',
    value: 'diffSumAmount',
    type: 'column',
    permission: !proxy.$permission('inventories:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
    show: false,
  },
}
leftTableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
rightTableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getLeftCustomize()
getRightCustomize()
</script>
<style lang="scss" scoped>
.table-top-msg {
  width: 100%;
  display: flex;
  align-items: center;
  .table-top-msg-left,
  .table-top-msg-right {
    width: 50%;
    display: flex;
    align-items: center;
  }
  .table-top-msg-left {
    justify-content: flex-end;
  }
  .table-top-msg-right {
    justify-content: flex-start;
  }
}
</style>
>
